All files / src/ucc-bridge ucc-bridge.ts

92.31% Statements 24/26
72.73% Branches 8/11
100% Functions 3/3
91.3% Lines 21/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 431x   1x 1x 1x 1x 1x   1x             1x 9x 9x 2x 7x   7x 6x   1x 1x         1x 5x   5x     5x     5x      
import { ipcMain, IpcMainEvent } from "electron"
import { UccBridgeEvent } from "./neon-connector"
import { setupUccConnection, UccClient } from "./ucc-connector"
import { sendIdleEvent } from "./events/idle-event"
import { sendStartedEvent } from "./events/start-event"
import { sendRunningEvent } from "./events/running-event"
import { sendEndedEvent } from "./events/ended-event"
 
export const defaultEventBinding: Record<string, (data: any) => Record<string, any>> = {
  idle: sendIdleEvent,
  started: sendStartedEvent,
  running: sendRunningEvent,
  ended: sendEndedEvent
}
 
export const routeEvent = (uccClient: UccClient, eventBindings: Record<string, (data: any) => any>) => {
  return (ipcEvent: IpcMainEvent, event: UccBridgeEvent): void => {
    if (event.type === "connected") {
      ipcEvent.reply("event-response", { eventId: event.eventId, connected: uccClient.isConnected })
    } else Iif (! uccClient.isConnected) {
      ipcEvent.reply("event-response", { eventId: event.eventId, error: `Not connect to the ucc-client` })
    } else if (eventBindings.hasOwnProperty(event.type)) {
      uccClient.sendEvent(ipcEvent, event.eventId, eventBindings[event.type](event.data))
    } else {
      console.log("Unknown event type: ", event)
      ipcEvent.reply("event-response", { eventId: event.eventId, error: `Unknown event type: ${event.type}` })
    }
  }
}
 
export const setupUccBridge = async (connectionUuId: string, port: number,
  IeventBinding: Record<string, (data: any) => void> = defaultEventBinding)
                                        : Promise<UccClient> => {
  const uccClient = await setupUccConnection(connectionUuId, port)
 
  // In the unit-test we have no ipcMain instance (not mockable?)
  Iif (ipcMain) {
    ipcMain.on("ucc-bridge", routeEvent(uccClient, eventBinding))
  }
  return uccClient
}